﻿using System;
using static System.Console;

namespace App.Console
{
    public static class NewtonRaphson
    {
        public delegate double SolveForX(double x);
        private const int MaxIterations = 50;
        private const double Tolerance = 0.0000001;
        public static void Solve(double guess, SolveForX forX, SolveForX devForX)
        {
            BackgroundColor = ConsoleColor.DarkBlue;
            ForegroundColor = ConsoleColor.White;

            var xn = guess;
            for (var i = 1; i <= MaxIterations; i++)
            {
                var xn1 = xn - forX(xn) / devForX(xn);
                WriteLine("|     {0,-10} | {1,15:0.00000} | {2,15:0.00000} | {3,15:0.00000} |       ", i, xn, forX(xn), devForX(xn));

                if(Math.Abs(xn - xn1) < Tolerance)
                {
                    WriteLine("Root = {0,15:0.00000}".PadRight(WindowWidth), xn1);
                    break;
                }

                xn = xn1;
            }
        }
        
        public static double QuadraticFunction(double x)
        {
            return 2 * x * x - 3 * x + 1;
        }

        public static double DevQuadraticFunction(double x)
        {
            return 4 * x - 3;
        }

        public static double CubicFunction(double x)
        {
            return x * x * x - 5.0 * x + 5.0;
        }

        public static double DevCubicFunction(double x)
        {
            return 3.0 * x * x - 5.0;
        }
    }
}
